/*
 * Copyright (C) 2025 Thomas Akehurst
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.tomakehurst.wiremock.db.config;

import com.github.tomakehurst.wiremock.common.NotWritableException;
import com.github.tomakehurst.wiremock.db.service.MultiMappingService;
import com.github.tomakehurst.wiremock.db.service.StubMappingService;
import com.github.tomakehurst.wiremock.standalone.MappingsSource;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import com.github.tomakehurst.wiremock.stubbing.StubMappings;
import java.util.List;
import java.util.UUID;

public class DatabaseMappingsSource implements MappingsSource {
  private final StubMappingService stubService;
  private final MultiMappingService multiService;
  // 记录多存根文件中的存根ID（用于判断是否为只读）
  private final List<UUID> multiMappingStubIds;

  public DatabaseMappingsSource(StubMappingService stubService, MultiMappingService multiService) {
    this.stubService = stubService;
    this.multiService = multiService;
    // 初始化时加载所有多存根文件中的存根ID，标记为只读
    this.multiMappingStubIds =
        multiService.findAllAsStubMappings().stream()
            .map(StubMapping::getId)
            .collect(java.util.stream.Collectors.toList());
  }

  @Override
  public void save(List<StubMapping> stubMappings) {
    for (StubMapping mapping : stubMappings) {
      save(mapping);
    }
  }

  @Override
  public void save(StubMapping stubMapping) {
    // 多存根文件中的存根只读，禁止单独保存
    if (multiMappingStubIds.contains(stubMapping.getId())) {
      throw new NotWritableException("Stubs from multi-mapping files are read-only");
    }
    stubService.save(stubMapping);
    stubMapping.setDirty(false);
  }

  @Override
  public void remove(UUID stubMappingId) {
    // 多存根文件中的存根禁止单独删除
    if (multiMappingStubIds.contains(stubMappingId)) {
      throw new NotWritableException("Stubs from multi-mapping files are read-only");
    }
    stubService.deleteById(stubMappingId);
  }

  @Override
  public void removeAll() {
    // 若存在多存根文件，禁止删除所有（避免误删只读数据）
    if (!multiMappingStubIds.isEmpty()) {
      throw new NotWritableException("Cannot remove all: multi-mapping stubs exist");
    }
    stubService.deleteAll();
  }

  @Override
  public void loadMappingsInto(StubMappings stubMappings) {
    // 1. 加载单存根
    List<StubMapping> singleMappings = stubService.findAll();
    singleMappings.forEach(
        mapping -> {
          mapping.setDirty(false);
          stubMappings.addMapping(mapping);
        });

    // 2. 加载多存根文件中的存根
    List<StubMapping> multiMappings = multiService.findAllAsStubMappings();
    multiMappings.forEach(
        mapping -> {
          mapping.setDirty(false);
          stubMappings.addMapping(mapping);
        });
  }
}
